export class Eraser {
  onBegin(point) {
    this.onMove(null, point);
  }

  onMove(from, to) {
    const ctx = this.ctx;
    const toVertex = this.getVertex(to);
    ctx.beginPath();
    ctx.fillStyle = this.option.backgroundColor;
    ctx.moveTo(toVertex.x1, toVertex.y1);
    // 画矩形
    ctx.lineTo(toVertex.x2, toVertex.y2);
    ctx.lineTo(toVertex.x3, toVertex.y3);
    ctx.lineTo(toVertex.x4, toVertex.y4);
    ctx.lineTo(toVertex.x1, toVertex.y1);
    ctx.fill();
    // 画连接矩形
    if (!!from) {
      const fromVertex = this.getVertex(from);
      const [sideVertex1, sideVertex2] = this.findSideVertex(from, to);
      ctx.moveTo(toVertex[sideVertex1[0]], toVertex[sideVertex1[1]]);
      ctx.lineTo(toVertex[sideVertex2[0]], toVertex[sideVertex2[1]]);
      ctx.lineTo(fromVertex[sideVertex2[0]], fromVertex[sideVertex2[1]]);
      ctx.lineTo(fromVertex[sideVertex1[0]], fromVertex[sideVertex1[1]]);
      ctx.lineTo(toVertex[sideVertex1[0]], toVertex[sideVertex1[1]]);
      ctx.fill();
    }
    ctx.closePath();
    // ctx.stroke();
  }

  // 寻找链接顶点
  findSideVertex({x: x1, y: y1}, {x: x2, y: y2}) {
    let r;
    switch (true) {
      case x1 === x2:
        r = [['x1', 'y1'], ['x2', 'y2']];
        break;
      case y1 === y2:
        r = [['x1', 'y1'], ['x4', 'y4']];
        break;
      case (x1 > x2 && y1 > y2) || (x1 < x2 && y1 < y2):
        r = [['x2', 'y2'], ['x4', 'y4']];
        break;
      default:
        r = [['x1', 'y1'], ['x3', 'y3']];
    }
    return r;
  }

  // 计算方块坐标
  getVertex({x, y}) {
    const pxWidth = this.option.pxWidth;
    const xl = x - pxWidth,
      xr = x + pxWidth,
      yt = y - pxWidth,
      yd = y + pxWidth;

    return {
      x1: xl,
      y1: yt,
      x2: xr,
      y2: yt,
      x3: xr,
      y3: yd,
      x4: xl,
      y4: yd,
    };
  }
}